package com.scs.application.modules.sys.security;

import com.alibaba.fastjson.JSON;
import com.scs.application.core.utils.WebUtils;
import com.scs.application.modules.sys.model.RestResult;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExpiredCredentialsException;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.List;

/**
 *
 */
public class AccessTokenFilter extends AuthenticatingFilter {

    private List<String> whiteList = Lists.newArrayList();

    @Override
    protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        //获取请求token
        String token = WebUtils.getAccessToken((HttpServletRequest)servletRequest);

        if (StringUtils.isBlank(token)) {
            return null;
        }

        return new AccessToken(token);
    }

    /**
     * 表示是否允许访问，如果允许访问返回true，否则返回false
     * @param request
     * @param response
     * @param mappedValue
     * @return
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        HttpServletRequest req = (HttpServletRequest) request;
        if (req.getMethod().equals(RequestMethod.OPTIONS.name()) || whiteList.contains(req.getRequestURI())) {
            return true;
        }
        return false;
    }

    /**
     * 表示当访问拒绝时是否已经处理了；如果返回 true 表示需要继续处理；如果返回 false 表示该拦截器实例已经处理了，将直接返回即可。
     * @param servletRequest
     * @param servletResponse
     * @return
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        //获取请求token，如果token不存在，直接返回401
        String token = WebUtils.getAccessToken((HttpServletRequest)servletRequest);
        if (StringUtils.isBlank(token)) {
            HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
            httpResponse.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);

            String json = JSON.toJSONString(RestResult.error(HttpStatus.UNAUTHORIZED, "您还未登录，请先登录", null));
            httpResponse.setStatus(HttpStatus.UNAUTHORIZED.value());

            httpResponse.getWriter().print(json);

            return false;
        }
        AccessToken accessToken = new AccessToken(token);
        try{
            SecurityUtils.getSubject().login(accessToken);
            return true;
        }catch (AuthenticationException e){
            onLoginFailure(accessToken,e,servletRequest,servletResponse);
            return false;
        }
    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        String json ;
        if (e instanceof ExpiredCredentialsException) {
            json = JSON.toJSONString(RestResult.error(HttpStatus.UNAUTHORIZED, "token已过期，请重新登录.", Collections.singletonMap("needLogin",true)));
        }else{
            json = JSON.toJSONString(RestResult.error(HttpStatus.UNAUTHORIZED, e.getMessage(),null));

        }
        httpResponse.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        httpResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
        try {
            httpResponse.getWriter().print(json);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return false;
    }

    @Override
    protected void postHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpResponse.setHeader("Access-Control-Allow-Origin", ((HttpServletRequest) request).getHeader("Origin"));

    }

}
